var npin = require("@native.pin");
require("eventbus.js");

//mode
IN        = 0;
OUT       = 1;
IRQ       = 2;
ANALOG    = 3;

//pull
NOPULL    = 0;
PULLUP    = 1;
PULLDOWN  = 2;

//level
LOW       = 0;
HIGH      = 1;

//irq
EVENT_RISING    = "rising";
EVENT_FALLING   = "falling";
EVENT_BOTH      = "both";

function Gpio(id){
    this.__id__ = -1;

    this.id = id;
    this.eventlist = {};

    this.read = function(){
        var level = npin.read(this.id);
        if(level == 0)
            return LOW;
        if(level == 1)
            return HIGH;
        return undefined;
    };

    this.write = function(level){
        if(level == undefined || typeof(level) != "number")
            return undefined;
        npin.write(this.id, level);
    };

    this.toggle = function(){
        npin.toggle(this.id);
    };

    this.on = function (event, callback) {
        if (
            event != EVENT_RISING &&
            event != EVENT_RISING &&
            event != EVENT_RISING
        )
            return undefined;
        if(typeof(callback) != "function")
            return undefined;
        
        this.__id__ = globalThis.eventbus.on(this, event, callback);
        npin.on(this.id, this.__id__, event);
    };

    this.close = function () {
        npin.close(this.id);
    };
}

function open(opt) {
    if(opt == undefined)
        return undefined;

    var index = opt["index"];
    var mode = opt["mode"];
    var pull = opt["pull"];
    var level = opt["level"];

    if (
        index == undefined ||
        mode == undefined ||
        typeof index != "number" ||
        typeof mode != "number"
    )
        return undefined;
    if (pull == undefined || typeof pull != "number") pull = NOPULL;
    if (level == undefined || typeof level != "number") level = LOW;

    if (npin.setup(index, mode, pull, level) >= 0) {
        return new Gpio(index);
    }
    return undefined;
}
